<!DOCTYPE html>












  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
    
  
  <link href="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.4.1/dist/jquery.fancybox.min.css" rel="stylesheet" type="text/css">




  
  
  
  

  

  

  

  
    

    
  

  

  
    
    
    <link href="//fonts.loli.net/css?family=Damion:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=6.6.0" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=6.6.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=6.6.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=6.6.0">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=6.6.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '6.6.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    fastclick: false,
    lazyload: true,
    tabs: true,
    motion: {"enable":true,"async":true,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="安装mongoDB官网下载安装（Windows安装方法） 基础知识集合——对应关系数据库中的表 文档——对应关系数据库中的行 启动数据库服务定位到安装目录下的bin文件夹里后 &amp;gt; mongod --dbpath ../data/db 如没有data/db文件夹，需先创建，dbpath用于指定数据存放位置">
<meta name="keywords" content="mongoDB">
<meta property="og:type" content="article">
<meta property="og:title" content="mongoDB常用命令">
<meta property="og:url" content="https://raincal.gitee.io/blog/post/mongodb-command/index.html">
<meta property="og:site_name" content="Raincal&#39;s Blog">
<meta property="og:description" content="安装mongoDB官网下载安装（Windows安装方法） 基础知识集合——对应关系数据库中的表 文档——对应关系数据库中的行 启动数据库服务定位到安装目录下的bin文件夹里后 &amp;gt; mongod --dbpath ../data/db 如没有data/db文件夹，需先创建，dbpath用于指定数据存放位置">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-09-01T09:33:26.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="mongoDB常用命令">
<meta name="twitter:description" content="安装mongoDB官网下载安装（Windows安装方法） 基础知识集合——对应关系数据库中的表 文档——对应关系数据库中的行 启动数据库服务定位到安装目录下的bin文件夹里后 &amp;gt; mongod --dbpath ../data/db 如没有data/db文件夹，需先创建，dbpath用于指定数据存放位置">



  <link rel="alternate" href="/blog/atom.xml" title="Raincal's Blog" type="application/atom+xml">




  <link rel="canonical" href="https://raincal.gitee.io/blog/post/mongodb-command/">



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>mongoDB常用命令 | Raincal's Blog</title>
  




<script async src="https://www.googletagmanager.com/gtag/js?id=UA-89637345-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-89637345-1');
</script>








  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Raincal's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/blog/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/blog/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/blog/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/blog/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-photos">

    
    
    
      
    

    

    <a href="/blog/photos/" rel="section"><i class="menu-item-icon fa fa-fw fa-camera-retro"></i> <br>photos</a>

  </li>

      
      
    </ul>
  

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://raincal.gitee.io/blog/blog/post/mongodb-command/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Raincal">
      <meta itemprop="description" content="El Psy Congroo">
      <meta itemprop="image" content="https://cdn-1256167913.image.myqcloud.com/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Raincal's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">mongoDB常用命令
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2015-07-10 16:47:56" itemprop="dateCreated datePublished" datetime="2015-07-10T16:47:56+08:00">2015-07-10</time>
            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing"><a href="/blog/categories/mongoDB/" itemprop="url" rel="index"><span itemprop="name">mongoDB</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h1><p><a href="https://www.mongodb.org/" target="_blank" rel="noopener">mongoDB官网</a>下载安装（<a href="http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/" target="_blank" rel="noopener">Windows安装方法</a>）</p>
<h1 id="基础知识"><a href="#基础知识" class="headerlink" title="基础知识"></a>基础知识</h1><p>集合——对应关系数据库中的表</p>
<p>文档——对应关系数据库中的行</p>
<h1 id="启动数据库服务"><a href="#启动数据库服务" class="headerlink" title="启动数据库服务"></a>启动数据库服务</h1><p>定位到安装目录下的bin文件夹里后</p>
<pre><code>&gt; mongod --dbpath ../data/db
</code></pre><p>如没有<code>data/db</code>文件夹，需先创建，<code>dbpath</code>用于指定数据存放位置</p>
<a id="more"></a>
<h1 id="开启一个客户端访问数据库"><a href="#开启一个客户端访问数据库" class="headerlink" title="开启一个客户端访问数据库"></a>开启一个客户端访问数据库</h1><p>同样的bin文件夹下执行</p>
<pre><code>&gt; mongo
</code></pre><p>默认连接至<code>test</code>数据库</p>
<h1 id="显示帮助"><a href="#显示帮助" class="headerlink" title="显示帮助"></a>显示帮助</h1><pre><code>&gt; help
</code></pre><h1 id="显示所有数据库名称"><a href="#显示所有数据库名称" class="headerlink" title="显示所有数据库名称"></a>显示所有数据库名称</h1><pre><code>&gt; show dbs
</code></pre><h1 id="切换数据库"><a href="#切换数据库" class="headerlink" title="切换数据库"></a>切换数据库</h1><pre><code>&gt; use test
</code></pre><h1 id="显示当前连接的数据库名称"><a href="#显示当前连接的数据库名称" class="headerlink" title="显示当前连接的数据库名称"></a>显示当前连接的数据库名称</h1><pre><code>&gt; db
</code></pre><h1 id="显示当前数据库所有集合"><a href="#显示当前数据库所有集合" class="headerlink" title="显示当前数据库所有集合"></a>显示当前数据库所有集合</h1><pre><code>&gt; show collections
</code></pre><h1 id="显示数据库支持的方法"><a href="#显示数据库支持的方法" class="headerlink" title="显示数据库支持的方法"></a>显示数据库支持的方法</h1><pre><code>&gt; db.help()
</code></pre><h1 id="显示集合支持的方法"><a href="#显示集合支持的方法" class="headerlink" title="显示集合支持的方法"></a>显示集合支持的方法</h1><pre><code>&gt; db.users.help()
</code></pre><h1 id="创建集合"><a href="#创建集合" class="headerlink" title="创建集合"></a>创建集合</h1><pre><code>&gt; db.createCollection(&quot;users&quot;)
</code></pre><h1 id="插入操作insert"><a href="#插入操作insert" class="headerlink" title="插入操作insert"></a>插入操作insert</h1><pre><code>&gt; db.users.insert({&quot;name&quot;:&quot;kiinlam&quot;,&quot;age&quot;:28})
</code></pre><h1 id="查询操作find"><a href="#查询操作find" class="headerlink" title="查询操作find"></a>查询操作find</h1><h2 id="查找所有文档"><a href="#查找所有文档" class="headerlink" title="查找所有文档"></a>查找所有文档</h2><pre><code>&gt; db.users.find()
</code></pre><h2 id="查找指定文档"><a href="#查找指定文档" class="headerlink" title="查找指定文档"></a>查找指定文档</h2><pre><code>&gt; db.users.find({&quot;name&quot;:&quot;kiinlam&quot;})
</code></pre><h2 id="查询一条"><a href="#查询一条" class="headerlink" title="查询一条"></a>查询一条</h2><pre><code>&gt; db.users.findOne({&quot;name&quot;:&quot;kiinlam&quot;})
</code></pre><h2 id="大于-gt"><a href="#大于-gt" class="headerlink" title="大于$gt"></a>大于$gt</h2><pre><code>&gt; db.users.find({&quot;age&quot;:{$gt:22}})
</code></pre><h2 id="大于等于-gte"><a href="#大于等于-gte" class="headerlink" title="大于等于$gte"></a>大于等于$gte</h2><pre><code>&gt; db.users.find({&quot;age&quot;:{$gte:22}})
</code></pre><h2 id="小于-lt"><a href="#小于-lt" class="headerlink" title="小于$lt"></a>小于$lt</h2><pre><code>&gt; db.users.find({&quot;age&quot;:{$lt:22}})
</code></pre><h2 id="小于等于-gte"><a href="#小于等于-gte" class="headerlink" title="小于等于$gte"></a>小于等于$gte</h2><pre><code>&gt; db.users.find({&quot;age&quot;:{$lte:22}})
</code></pre><h2 id="不等于-ne"><a href="#不等于-ne" class="headerlink" title="不等于$ne"></a>不等于$ne</h2><pre><code>&gt; db.users.find(&quot;age&quot;:{$ne:22})
</code></pre><h2 id="或-or"><a href="#或-or" class="headerlink" title="或$or"></a>或$or</h2><pre><code>&gt; db.users.find({$or:[{&quot;name&quot;:&quot;kiinlam&quot;},{&quot;name&quot;:&quot;cheungkiinlam&quot;}]})
</code></pre><h2 id="在集合中-in"><a href="#在集合中-in" class="headerlink" title="在集合中$in"></a>在集合中$in</h2><pre><code>&gt; db.users.find(&quot;name&quot;:{$in:[&quot;kiinlam&quot;,&quot;cheungkiinlam&quot;]})
</code></pre><h2 id="不在集合中-nin"><a href="#不在集合中-nin" class="headerlink" title="不在集合中$nin"></a>不在集合中$nin</h2><pre><code>&gt; db.users.find(&quot;name&quot;:{$nin:[&quot;kiinlam&quot;,&quot;cheungkiinlam&quot;]})
</code></pre><h2 id="正则查询"><a href="#正则查询" class="headerlink" title="正则查询"></a>正则查询</h2><pre><code>&gt; db.users.find({&quot;name&quot;:/^k/,&quot;name&quot;:/m$/})
</code></pre><h2 id="筛选查询-where"><a href="#筛选查询-where" class="headerlink" title="筛选查询$where"></a>筛选查询$where</h2><pre><code>// 使用js function作为筛选条件
&gt; db.users.find({$where: function(){return this.name==&apos;kiinlam&apos;}})
</code></pre><h2 id="限制查询数量limit"><a href="#限制查询数量limit" class="headerlink" title="限制查询数量limit"></a>限制查询数量limit</h2><pre><code>&gt; db.users.find({&quot;age&quot;:22}).limit(10)
</code></pre><h1 id="更新操作update"><a href="#更新操作update" class="headerlink" title="更新操作update"></a>更新操作update</h1><h2 id="指定文档全部更新，等于覆盖"><a href="#指定文档全部更新，等于覆盖" class="headerlink" title="指定文档全部更新，等于覆盖"></a>指定文档全部更新，等于覆盖</h2><pre><code>&gt; db.users.update({&quot;name&quot;:&quot;kiinlam&quot;}, {&quot;name&quot;:&quot;cheungkiinlam&quot;,&quot;age&quot;:27})
</code></pre><h2 id="局部更新一：增量更新-inc"><a href="#局部更新一：增量更新-inc" class="headerlink" title="局部更新一：增量更新$inc"></a>局部更新一：增量更新$inc</h2><pre><code>// age增加2，其他不变
&gt; db.users.update({&quot;name&quot;:&quot;kiinlam&quot;}, {$inc:{&quot;age&quot;:2}})
</code></pre><h2 id="局部更新二：字段修改-set"><a href="#局部更新二：字段修改-set" class="headerlink" title="局部更新二：字段修改$set"></a>局部更新二：字段修改$set</h2><pre><code>// age改为20
&gt; db.users.update({&quot;name&quot;:&quot;kiinlam&quot;}, {$set:{&quot;age&quot;:20}})
</code></pre><h2 id="新增更新：如果不存在，就新增一条"><a href="#新增更新：如果不存在，就新增一条" class="headerlink" title="新增更新：如果不存在，就新增一条"></a>新增更新：如果不存在，就新增一条</h2><pre><code>// 第三个参数为true
&gt; db.users.update({&quot;name&quot;:&quot;kiinlam&quot;}, {$set:{&quot;age&quot;:18}}, true)
</code></pre><h2 id="批量更新"><a href="#批量更新" class="headerlink" title="批量更新"></a>批量更新</h2><pre><code>// 如果匹配多条，默认只改第一条，将第四个参数设为true可全部更新
&gt; db.users.update({&quot;name&quot;:&quot;kiinlam&quot;}, {$set:{&quot;age&quot;:18}}, true, true)
</code></pre><h1 id="保存操作save"><a href="#保存操作save" class="headerlink" title="保存操作save"></a>保存操作save</h1><pre><code>// 插入新文档，如果不提供&quot;_id&quot;字段
&gt; db.users.save({&quot;name&quot;:&quot;kiinlam&quot;, &quot;age&quot;:28})
// 更新已存在的文档
&gt; db.users.save({&quot;_id&quot;:&quot;xxx&quot;,&quot;name&quot;:&quot;kiinlam&quot;, &quot;age&quot;:28})
</code></pre><h1 id="删除操作remove"><a href="#删除操作remove" class="headerlink" title="删除操作remove"></a>删除操作remove</h1><p>删除操作不可恢复</p>
<h2 id="删除所有，但不删除索引"><a href="#删除所有，但不删除索引" class="headerlink" title="删除所有，但不删除索引"></a>删除所有，但不删除索引</h2><pre><code>&gt; db.users.remove({})
</code></pre><h2 id="删除指定文档"><a href="#删除指定文档" class="headerlink" title="删除指定文档"></a>删除指定文档</h2><pre><code>&gt; db.users.remove({&quot;name&quot;:&quot;kiinlam&quot;})
</code></pre><h2 id="删除一条指定文档，如果有多条结果"><a href="#删除一条指定文档，如果有多条结果" class="headerlink" title="删除一条指定文档，如果有多条结果"></a>删除一条指定文档，如果有多条结果</h2><pre><code>&gt; db.users.remove({&quot;name&quot;:&quot;kiinlam&quot;}, true)
</code></pre><p>完全删除集合，包括索引，应当使用<code>drop</code></p>
<p>大量删除时，采用复制需要保留的文档到新集合，再用<code>drop</code>删除集合。</p>
<h1 id="删除数据库"><a href="#删除数据库" class="headerlink" title="删除数据库"></a>删除数据库</h1><pre><code>&gt; db.dropDatabase()
</code></pre><h1 id="删除集合"><a href="#删除集合" class="headerlink" title="删除集合"></a>删除集合</h1><pre><code>&gt; db.users.drop()
</code></pre><h1 id="计数操作count"><a href="#计数操作count" class="headerlink" title="计数操作count"></a>计数操作count</h1><pre><code>&gt; db.users.count()
&gt; db.users.count({&quot;age&quot;:29})
</code></pre><h1 id="唯一值查询distinct"><a href="#唯一值查询distinct" class="headerlink" title="唯一值查询distinct"></a>唯一值查询distinct</h1><h2 id="指定字段有多个相同时，只取一个，返回指定字段的值组合成的数组"><a href="#指定字段有多个相同时，只取一个，返回指定字段的值组合成的数组" class="headerlink" title="指定字段有多个相同时，只取一个，返回指定字段的值组合成的数组"></a>指定字段有多个相同时，只取一个，返回指定字段的值组合成的数组</h2><pre><code>&gt; db.users.distinct(&quot;age&quot;)
</code></pre><h1 id="分组操作group"><a href="#分组操作group" class="headerlink" title="分组操作group"></a>分组操作group</h1><p>按照<code>age</code>进行分组操作，分组结果存放在<code>user</code>中，值为对应<code>age</code>的name值的数组</p>
<p><code>key</code>：分组依据</p>
<p><code>initial</code>：初始化函数，每个不同的age组共享同一个函数</p>
<p><code>$reduce</code>： 第一个参数为当前文档，第二参数为前一次函数操作的累计对象，第一次为<code>initial</code>对应的对象</p>
<pre><code>&gt; db.users.group({
                    &quot;key&quot;: {&quot;age&quot;: true},
                    &quot;initial&quot;: {&quot;user&quot;: []},
                    &quot;$reduce&quot;: function(cur,prev){
                        prev.user.push(cur.name);
                    }
                })
</code></pre><p>假设有数据如下：</p>
<pre><code>{ &quot;_id&quot; : ObjectId(&quot;55910457607379845607d9e2&quot;), &quot;name&quot; : &quot;kiinlam&quot;, &quot;age&quot; : 29 }
{ &quot;_id&quot; : ObjectId(&quot;55910468607379845607d9e3&quot;), &quot;name&quot; : &quot;shadow&quot;, &quot;age&quot; : 26 }
{ &quot;_id&quot; : ObjectId(&quot;55910992607379845607d9e5&quot;), &quot;name&quot; : &quot;foo&quot;, &quot;age&quot; : 29 }
{ &quot;_id&quot; : ObjectId(&quot;55911fca607379845607d9e6&quot;), &quot;name&quot; : &quot;dd&quot;, &quot;age&quot; : 22 }
{ &quot;_id&quot; : ObjectId(&quot;55911fd3607379845607d9e7&quot;), &quot;name&quot; : &quot;mm&quot;, &quot;age&quot; : 22 }
{ &quot;_id&quot; : ObjectId(&quot;55911fdf607379845607d9e8&quot;), &quot;name&quot; : &quot;gg&quot;, &quot;age&quot; : 22 }
{ &quot;_id&quot; : ObjectId(&quot;55911feb607379845607d9e9&quot;), &quot;name&quot; : &quot;jj&quot;, &quot;age&quot; : 22 }
{ &quot;_id&quot; : ObjectId(&quot;55920545ff40738c1fd0a839&quot;), &quot;name&quot; : &quot;zz&quot;, &quot;age&quot; : 1 }
</code></pre><p>分组结果为：</p>
<pre><code>[
        {
                &quot;age&quot; : 29,
                &quot;user&quot; : [
                        &quot;kiinlam&quot;,
                        &quot;foo&quot;
                ]
        },
        {
                &quot;age&quot; : 26,
                &quot;user&quot; : [
                        &quot;shadow&quot;
                ]
        },
        {
                &quot;age&quot; : 22,
                &quot;user&quot; : [
                        &quot;dd&quot;,
                        &quot;mm&quot;,
                        &quot;gg&quot;,
                        &quot;jj&quot;
                ]
        },
        {
                &quot;age&quot; : 1,
                &quot;user&quot; : [
                        &quot;zz&quot;
                ]
        }
]
</code></pre><h2 id="更多分组功能"><a href="#更多分组功能" class="headerlink" title="更多分组功能"></a>更多分组功能</h2><p>可选参数: <code>condition</code> 和 <code>finalize</code>。</p>
<pre><code>`condition` —— 过滤条件
`finalize` —— 函数，分组完成后执行
</code></pre><p>过滤掉<code>age</code>大于22的文档，增加属性标明分组中文档的数量</p>
<pre><code>&gt; db.users.group({
                    &quot;key&quot;: {&quot;age&quot;: true},
                    &quot;initial&quot;: {&quot;user&quot;: []},
                    &quot;$reduce&quot;: function(cur,prev){
                        prev.user.push(cur.name);
                    },
                    &quot;condition&quot;: {&quot;age&quot;:{$lte:22}},
                    &quot;finalize&quot;: function(out){
                        out.count = out.user.length;
                    }
                })
</code></pre><p>分组结果为：</p>
<pre><code>[
        {
                &quot;age&quot; : 22,
                &quot;user&quot; : [
                        &quot;dd&quot;,
                        &quot;mm&quot;,
                        &quot;gg&quot;,
                        &quot;jj&quot;
                ],
                &quot;count&quot; : 4
        },
        {
                &quot;age&quot; : 1,
                &quot;user&quot; : [
                        &quot;zz&quot;
                ],
                &quot;count&quot; : 1
        }
]
</code></pre><h1 id="mapReduce"><a href="#mapReduce" class="headerlink" title="mapReduce"></a>mapReduce</h1><p><code>map</code>：映射函数，内部调用<code>emit(key,value)</code>，集合按照<code>key</code>进行映射分组。</p>
<p><code>reduce</code>：简化函数，对<code>map</code>分组后的数据进行分组简化，<code>reduce(key,value)</code>中的<code>key</code>是<code>emit</code>中的<code>key</code>，而<code>value</code>则是<code>emit</code>分组结果的集合。</p>
<p><code>mapReduce</code>：最后执行的函数，参数为<code>map</code>、<code>reduce</code>和一些可选参数。</p>
<pre><code>&gt; db.users.mapReduce
function ( map , reduce , optionsOrOutString ){
    var c = { mapreduce : this._shortName , map : map , reduce : reduce };
    assert( optionsOrOutString , &quot;need to supply an optionsOrOutString&quot; )

    if ( typeof( optionsOrOutString ) == &quot;string&quot; )
        c[&quot;out&quot;] = optionsOrOutString;
    else
        Object.extend( c , optionsOrOutString );

    var raw = this._db.runCommand( c );
    if ( ! raw.ok ){
        __mrerror__ = raw;
        throw Error( &quot;map reduce failed:&quot; + tojson(raw) );
    }
    return new MapReduceResult( this._db , raw );

}
</code></pre><p>创建<code>map</code>函数</p>
<pre><code>function (){
    emit(this.name,{count:1});
}
</code></pre><p>创建<code>reduce</code>函数</p>
<pre><code>function (key,value){
    var result = {count:0};
    for(var i = 0; i &lt; value.length; i++){
        result.count += value[i].count;
    }
    return result;
}
</code></pre><p>执行<code>mapReduce</code>操作</p>
<pre><code>&gt; db.users.mapReduce(map,reduce,{&quot;out&quot;:&quot;collection&quot;})
</code></pre><p>假设有数据如下</p>
<pre><code>{ &quot;_id&quot; : ObjectId(&quot;55910457607379845607d9e2&quot;), &quot;name&quot; : &quot;kiinlam&quot;, &quot;age&quot; : 29 }
{ &quot;_id&quot; : ObjectId(&quot;55910468607379845607d9e3&quot;), &quot;name&quot; : &quot;shadow&quot;, &quot;age&quot; : 26 }
{ &quot;_id&quot; : ObjectId(&quot;55910992607379845607d9e5&quot;), &quot;name&quot; : &quot;foo&quot;, &quot;age&quot; : 29 }
{ &quot;_id&quot; : ObjectId(&quot;55920545ff40738c1fd0a839&quot;), &quot;name&quot; : &quot;zz&quot;, &quot;age&quot; : 1 }
{ &quot;_id&quot; : ObjectId(&quot;55911fca607379845607d9e6&quot;), &quot;name&quot; : &quot;foo&quot;, &quot;age&quot; : 22 }
{ &quot;_id&quot; : ObjectId(&quot;55911fd3607379845607d9e7&quot;), &quot;name&quot; : &quot;foo&quot;, &quot;age&quot; : 22 }
{ &quot;_id&quot; : ObjectId(&quot;55911fdf607379845607d9e8&quot;), &quot;name&quot; : &quot;foo&quot;, &quot;age&quot; : 22 }
{ &quot;_id&quot; : ObjectId(&quot;55911feb607379845607d9e9&quot;), &quot;name&quot; : &quot;foo&quot;, &quot;age&quot; : 22 }
</code></pre><p>输出结果</p>
<pre><code>{
        &quot;result&quot; : &quot;collection&quot;,    // 存放最终结果的集合名
        &quot;timeMillis&quot; : 28,
        &quot;counts&quot; : {
                &quot;input&quot; : 8,    // 传入文档的次数
                &quot;emit&quot; : 8,    // emit函数被调用次数
                &quot;reduce&quot; : 1,    // reduce函数被调用次数
                &quot;output&quot; : 4    // 最后返回文档的个数
        },
        &quot;ok&quot; : 1
}
</code></pre><p>查看集合<code>collection</code>中的结果</p>
<pre><code>&gt; db.collection.find()
</code></pre><p>输出结果</p>
<pre><code>{ &quot;_id&quot; : &quot;foo&quot;, &quot;value&quot; : { &quot;count&quot; : 5 } }
{ &quot;_id&quot; : &quot;kiinlam&quot;, &quot;value&quot; : { &quot;count&quot; : 1 } }
{ &quot;_id&quot; : &quot;shadow&quot;, &quot;value&quot; : { &quot;count&quot; : 1 } }
{ &quot;_id&quot; : &quot;zz&quot;, &quot;value&quot; : { &quot;count&quot; : 1 } }
</code></pre><h1 id="游标"><a href="#游标" class="headerlink" title="游标"></a>游标</h1><p>游标只表示一个引用，并不是真正的执行，在需要的时候，通过for循环或<code>next()</code>方法进行遍历读取，枚举结束后，游标销毁，不再返回数据。</p>
<p>申明一个游标</p>
<pre><code>&gt; var list = db.collection.find()
</code></pre><p>通过<code>forEach</code>遍历游标</p>
<pre><code>&gt; list.forEach(function(i){
      print(i._id);
  })
</code></pre><p>输出结果</p>
<pre><code>foo
kiinlam
shadow
zz
</code></pre><p>或者通过<code>next</code>遍历集合</p>
<pre><code>&gt; var list = db.collection.find()
&gt; list.next()
{ &quot;_id&quot; : &quot;foo&quot;, &quot;value&quot; : { &quot;count&quot; : 5 } }
&gt; list.next()
{ &quot;_id&quot; : &quot;kiinlam&quot;, &quot;value&quot; : { &quot;count&quot; : 1 } }
&gt; list.next()
{ &quot;_id&quot; : &quot;shadow&quot;, &quot;value&quot; : { &quot;count&quot; : 1 } }
&gt; list.next()
{ &quot;_id&quot; : &quot;zz&quot;, &quot;value&quot; : { &quot;count&quot; : 1 } }
&gt; list.next()
2015-07-01T11:27:38.186+0800 E QUERY    Error: error hasNext: false
    at Error (&lt;anonymous&gt;)
    at DBQuery.next (src/mongo/shell/query.js:255:15)
    at (shell):1:6 at src/mongo/shell/query.js:255
&gt; list
&gt;
</code></pre><h1 id="索引ensureIndex"><a href="#索引ensureIndex" class="headerlink" title="索引ensureIndex"></a>索引ensureIndex</h1><h2 id="建立索引"><a href="#建立索引" class="headerlink" title="建立索引"></a>建立索引</h2><pre><code>// 1为升序，-1为降序
&gt; db.users.ensureIndex({&quot;name&quot;:1})
</code></pre><h2 id="唯一索引"><a href="#唯一索引" class="headerlink" title="唯一索引"></a>唯一索引</h2><pre><code>&gt; db.users.ensureIndex({&quot;name&quot;:1},{&quot;unique&quot;:true})
</code></pre><h2 id="组合索引"><a href="#组合索引" class="headerlink" title="组合索引"></a>组合索引</h2><pre><code>&gt; db.users.ensureIndex({&quot;name&quot;:1, &quot;age&quot;:-1})
</code></pre><h2 id="查看索引"><a href="#查看索引" class="headerlink" title="查看索引"></a>查看索引</h2><pre><code>&gt; db.users.getIndexes()
</code></pre><h2 id="按指定索引查询"><a href="#按指定索引查询" class="headerlink" title="按指定索引查询"></a>按指定索引查询</h2><pre><code>&gt; db.users.find({&quot;name&quot;:&quot;kiinlam&quot;}).hint({&quot;name&quot;:1,&quot;age&quot;:1})
</code></pre><h2 id="删除索引"><a href="#删除索引" class="headerlink" title="删除索引"></a>删除索引</h2><pre><code>// 删除所有自定义索引
&gt; db.users.dropIndexes()
// 删除指定索引
&gt; db.users.dropIndex(&quot;name_1&quot;)
</code></pre><h1 id="性能分析函数explain"><a href="#性能分析函数explain" class="headerlink" title="性能分析函数explain"></a>性能分析函数explain</h1><pre><code>&gt; db.users.find().explain(&quot;executionStats&quot;)
</code></pre><h1 id="主从数据库部署"><a href="#主从数据库部署" class="headerlink" title="主从数据库部署"></a>主从数据库部署</h1><h2 id="创建主数据库master"><a href="#创建主数据库master" class="headerlink" title="创建主数据库master"></a>创建主数据库master</h2><pre><code>&gt; mongod --dbpath=XXX --master
</code></pre><h2 id="创建从数据库slave"><a href="#创建从数据库slave" class="headerlink" title="创建从数据库slave"></a>创建从数据库slave</h2><pre><code>// 指定从数据库端口--port
// 指定主数据库源--source
&gt; mongod --dbpath=XXX --port=8888 --slave --source=127.0.0.1:27017
</code></pre><h2 id="后期指定主数据库源"><a href="#后期指定主数据库源" class="headerlink" title="后期指定主数据库源"></a>后期指定主数据库源</h2><pre><code>&gt; mongod --dbpath=XXX --port=8888 --slave
// 后期添加源
// 切换到local数据库
&gt; use local
// 在sources中加入源地址
&gt; db.sources.insert({&quot;host&quot;:&quot;127.0.0.1:27017&quot;})
</code></pre><h1 id="副本集replSet"><a href="#副本集replSet" class="headerlink" title="副本集replSet"></a>副本集replSet</h1><p>该架构没有特定的主数据库，一个数据库宕机了，另一个数据库会顶上</p>
<h2 id="创建第一个数据库服务器"><a href="#创建第一个数据库服务器" class="headerlink" title="创建第一个数据库服务器"></a>创建第一个数据库服务器</h2><pre><code>// 需要指定集群名及下一个数据库地址
&gt; mongod --dbpath=XXX --port 2222 --replSet mySet/127.0.0.1:3333
</code></pre><h2 id="创建第二个数据库服务器"><a href="#创建第二个数据库服务器" class="headerlink" title="创建第二个数据库服务器"></a>创建第二个数据库服务器</h2><pre><code>&gt; mongod --dbpath=XXX --port 3333 --replSet mySet/127.0.0.1:2222
</code></pre><h2 id="初始化副本集"><a href="#初始化副本集" class="headerlink" title="初始化副本集"></a>初始化副本集</h2><pre><code>// 进入任一数据库的admin集合
&gt; mongo 127.0.0.1:2222/admin
// 执行初始化操作
&gt; db.runCommand({
                    &quot;replSetInitiate&quot;:{
                        &quot;_id&quot;:&quot;mySet&quot;,
                        &quot;members&quot;:[
                            {
                                &quot;_id&quot;:1,
                                &quot;host&quot;:&quot;127.0.0.1:2222&quot;
                            },
                            {
                                &quot;_id&quot;:2,
                                &quot;host&quot;:&quot;127.0.0.1:3333&quot;
                            }
                        ]
                    }
                })
</code></pre><h2 id="仲裁服务器"><a href="#仲裁服务器" class="headerlink" title="仲裁服务器"></a>仲裁服务器</h2><pre><code>// 启动仲裁服务器
&gt; mongod --dbpath=XXX --port 4444 --replSet mySet/127.0.0.1:2222
// 回到admin集合中添加仲裁服务器
&gt; mongo 127.0.0.1:2222/admin
&gt; rs.addArb(&quot;127.0.0.1:4444&quot;)
// 查看服务器集群状态
&gt; rs.status()
</code></pre><h1 id="分片技术"><a href="#分片技术" class="headerlink" title="分片技术"></a>分片技术</h1><p>将集合进行拆分，将拆分的数据均摊到几个分片上。</p>
<p>主要参与者：</p>
<ul>
<li>客户端</li>
<li>路由服务器mongos</li>
<li>配置服务器</li>
<li>分片数据库实例</li>
</ul>
<h2 id="开启配置服务器config"><a href="#开启配置服务器config" class="headerlink" title="开启配置服务器config"></a>开启配置服务器config</h2><pre><code>&gt; mongod --dbpath=XXX --port 2222
</code></pre><h2 id="开启路由服务器mongos"><a href="#开启路由服务器mongos" class="headerlink" title="开启路由服务器mongos"></a>开启路由服务器mongos</h2><pre><code>// 指定配置服务器
&gt; mongos --port 3333 --configdb=127.0.0.1:2222
</code></pre><h2 id="开启分片数据库服务器mongod"><a href="#开启分片数据库服务器mongod" class="headerlink" title="开启分片数据库服务器mongod"></a>开启分片数据库服务器mongod</h2><pre><code>&gt; mongod --dbpath=XXX --port 4444
&gt; mongod --dbpath=XXX --port 5555
</code></pre><h2 id="服务配置"><a href="#服务配置" class="headerlink" title="服务配置"></a>服务配置</h2><pre><code>// 进入mongos数据库admin集合
&gt; mongo 127.0.0.1:3333/admin
// 添加分片服务器addshard
&gt; db.runCommand({
                    &quot;addshard&quot;:&quot;127.0.0.1:4444&quot;,
                    &quot;allowLocal&quot;:true
                })
&gt; db.runCommand({
                    &quot;addshard&quot;:&quot;127.0.0.1:5555&quot;,
                    &quot;allowLocal&quot;:true
                })
// 开启数据库test的分片功能enablesharding
&gt; db.runCommand({&quot;enablesharding&quot;:&quot;test&quot;})
// 指定集合中分片的片键users.name
&gt; db.runCommand({&quot;shardcollection&quot;:&quot;test.users&quot;,&quot;key&quot;:{&quot;name&quot;:1}})
// 在mongos中查看数据分片情况
&gt; use test
&gt; db.printShardingStatus()
</code></pre><h1 id="运维"><a href="#运维" class="headerlink" title="运维"></a>运维</h1><p>运维通常会涉及到以下4个方面</p>
<ul>
<li>安装部署</li>
<li>状态监控</li>
<li>安全认证</li>
<li>备份和恢复</li>
</ul>
<h2 id="安装部署为windows服务"><a href="#安装部署为windows服务" class="headerlink" title="安装部署为windows服务"></a>安装部署为windows服务</h2><pre><code>// 指定日志路径，添加install参数
&gt; mongod --dbpath=XXX --logpath=XXX --port=2222 --install
// 启动服务
&gt; net start MongoDB
</code></pre><h2 id="状态监控"><a href="#状态监控" class="headerlink" title="状态监控"></a>状态监控</h2><h3 id="静态统计"><a href="#静态统计" class="headerlink" title="静态统计"></a>静态统计</h3><p><em>db.stats()</em></p>
<pre><code>// 查看单个数据库状态
&gt; db.stats()
</code></pre><p><code>stats</code>比较简单，可以参考<a href="http://www.cnblogs.com/xuegang/archive/2011/10/13/2209965.html" target="_blank" rel="noopener">db.stats()</a>一文</p>
<p><em>db.serverStatus()</em></p>
<pre><code>// 查看整个mongodb的状态
// 进入admin集合
&gt; mongo 127.0.0.1:2222/admin
// 查看状态
&gt; db.serverStatus()
</code></pre><p><code>serverStatus</code>的参数很多，可以参考<a href="http://www.cnblogs.com/xuegang/archive/2011/10/13/2210339.html" target="_blank" rel="noopener">db.serverStatus()</a>一文</p>
<h3 id="实时统计"><a href="#实时统计" class="headerlink" title="实时统计"></a>实时统计</h3><pre><code>&gt; mongostat --port 2222
</code></pre><h2 id="安全认证"><a href="#安全认证" class="headerlink" title="安全认证"></a>安全认证</h2><p><em>TODO</em></p>
<p>有点复杂，偷懒了，参考<a href="http://docs.mongodb.org/manual/security/" target="_blank" rel="noopener">安全认证</a></p>
<h2 id="备份和恢复"><a href="#备份和恢复" class="headerlink" title="备份和恢复"></a>备份和恢复</h2><pre><code>// 备份test数据库到D:\mongodb\backup
&gt; mongodump --port 2222 -d test -o D:\mongodb\backup
// 恢复数据，drop表示恢复前删除原有数据
&gt; mongorestore --port 2222 -d test --drop D:\mongodb\backup
</code></pre><hr>
<h2 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h2><ul>
<li><a href="https://www.mongodb.org/" target="_blank" rel="noopener">mongoDB</a></li>
<li><a href="http://docs.mongodb.org/manual/" target="_blank" rel="noopener">MongoDB文档</a></li>
<li><a href="http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/" target="_blank" rel="noopener">install-mongodb-on-windows</a></li>
<li><a href="http://www.cnblogs.com/huangxincheng/category/355399.html" target="_blank" rel="noopener">8天学通MongoDB系列</a></li>
</ul>

      
    </div>

    
      


    

    
    
    

    

    
       
    
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/mongoDB/" rel="tag"># mongoDB</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/post/launch-sublime-text-from-command-line/" rel="next" title="Mac OS终端使用subl运行Sublime Text 3">
                <i class="fa fa-chevron-left"></i> Mac OS终端使用subl运行Sublime Text 3
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/post/lodash/" rel="prev" title="10 个可用 ES6 替代的 Lodash 特性">
                10 个可用 ES6 替代的 Lodash 特性 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="https://cdn-1256167913.image.myqcloud.com/images/avatar.png" alt="Raincal">
            
              <p class="site-author-name" itemprop="name">Raincal</p>
              <p class="site-description motion-element" itemprop="description">El Psy Congroo</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/blog/archives/">
                
                    <span class="site-state-item-count">9</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">3</span>
                    <span class="site-state-item-name">分类</span>
                  
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/blog/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">17</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/blog/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                  
                    
                  
                  <a href="https://github.com/Raincal" title="GitHub &rarr; https://github.com/Raincal" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i></a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                  
                    
                  
                  <a href="https://twitter.com/cyj228" title="Twitter &rarr; https://twitter.com/cyj228" rel="noopener" target="_blank"><i class="fa fa-fw fa-twitter"></i></a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                  
                    
                  
                  <a href="https://weibo.com/cyj228" title="Weibo &rarr; https://weibo.com/cyj228" rel="noopener" target="_blank"><i class="fa fa-fw fa-weibo"></i></a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                  
                    
                  
                  <a href="https://t.me/Raincal" title="Telegram &rarr; https://t.me/Raincal" rel="noopener" target="_blank"><i class="fa fa-fw fa-telegram"></i></a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                  
                    
                  
                  <a href="mailto:cyj94228@gmail.com" title="E-Mail &rarr; mailto:cyj94228@gmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i></a>
                </span>
              
            </div>
          

          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://blog.raincal.com" title="https://blog.raincal.com" rel="noopener" target="_blank">RAINCAL</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://status.raincal.com" title="https://status.raincal.com" rel="noopener" target="_blank">UPTIME</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.fangr.cc" title="https://www.fangr.cc" rel="noopener" target="_blank">Fong Ray's Blog</a>
                  </li>
                
              </ul>
            </div>
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#安装"><span class="nav-number">1.</span> <span class="nav-text">安装</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#基础知识"><span class="nav-number">2.</span> <span class="nav-text">基础知识</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#启动数据库服务"><span class="nav-number">3.</span> <span class="nav-text">启动数据库服务</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#开启一个客户端访问数据库"><span class="nav-number">4.</span> <span class="nav-text">开启一个客户端访问数据库</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#显示帮助"><span class="nav-number">5.</span> <span class="nav-text">显示帮助</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#显示所有数据库名称"><span class="nav-number">6.</span> <span class="nav-text">显示所有数据库名称</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#切换数据库"><span class="nav-number">7.</span> <span class="nav-text">切换数据库</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#显示当前连接的数据库名称"><span class="nav-number">8.</span> <span class="nav-text">显示当前连接的数据库名称</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#显示当前数据库所有集合"><span class="nav-number">9.</span> <span class="nav-text">显示当前数据库所有集合</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#显示数据库支持的方法"><span class="nav-number">10.</span> <span class="nav-text">显示数据库支持的方法</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#显示集合支持的方法"><span class="nav-number">11.</span> <span class="nav-text">显示集合支持的方法</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#创建集合"><span class="nav-number">12.</span> <span class="nav-text">创建集合</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#插入操作insert"><span class="nav-number">13.</span> <span class="nav-text">插入操作insert</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#查询操作find"><span class="nav-number">14.</span> <span class="nav-text">查询操作find</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#查找所有文档"><span class="nav-number">14.1.</span> <span class="nav-text">查找所有文档</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#查找指定文档"><span class="nav-number">14.2.</span> <span class="nav-text">查找指定文档</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#查询一条"><span class="nav-number">14.3.</span> <span class="nav-text">查询一条</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#大于-gt"><span class="nav-number">14.4.</span> <span class="nav-text">大于$gt</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#大于等于-gte"><span class="nav-number">14.5.</span> <span class="nav-text">大于等于$gte</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#小于-lt"><span class="nav-number">14.6.</span> <span class="nav-text">小于$lt</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#小于等于-gte"><span class="nav-number">14.7.</span> <span class="nav-text">小于等于$gte</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#不等于-ne"><span class="nav-number">14.8.</span> <span class="nav-text">不等于$ne</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#或-or"><span class="nav-number">14.9.</span> <span class="nav-text">或$or</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#在集合中-in"><span class="nav-number">14.10.</span> <span class="nav-text">在集合中$in</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#不在集合中-nin"><span class="nav-number">14.11.</span> <span class="nav-text">不在集合中$nin</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#正则查询"><span class="nav-number">14.12.</span> <span class="nav-text">正则查询</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#筛选查询-where"><span class="nav-number">14.13.</span> <span class="nav-text">筛选查询$where</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#限制查询数量limit"><span class="nav-number">14.14.</span> <span class="nav-text">限制查询数量limit</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#更新操作update"><span class="nav-number">15.</span> <span class="nav-text">更新操作update</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#指定文档全部更新，等于覆盖"><span class="nav-number">15.1.</span> <span class="nav-text">指定文档全部更新，等于覆盖</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#局部更新一：增量更新-inc"><span class="nav-number">15.2.</span> <span class="nav-text">局部更新一：增量更新$inc</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#局部更新二：字段修改-set"><span class="nav-number">15.3.</span> <span class="nav-text">局部更新二：字段修改$set</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#新增更新：如果不存在，就新增一条"><span class="nav-number">15.4.</span> <span class="nav-text">新增更新：如果不存在，就新增一条</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#批量更新"><span class="nav-number">15.5.</span> <span class="nav-text">批量更新</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#保存操作save"><span class="nav-number">16.</span> <span class="nav-text">保存操作save</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#删除操作remove"><span class="nav-number">17.</span> <span class="nav-text">删除操作remove</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#删除所有，但不删除索引"><span class="nav-number">17.1.</span> <span class="nav-text">删除所有，但不删除索引</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#删除指定文档"><span class="nav-number">17.2.</span> <span class="nav-text">删除指定文档</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#删除一条指定文档，如果有多条结果"><span class="nav-number">17.3.</span> <span class="nav-text">删除一条指定文档，如果有多条结果</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#删除数据库"><span class="nav-number">18.</span> <span class="nav-text">删除数据库</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#删除集合"><span class="nav-number">19.</span> <span class="nav-text">删除集合</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#计数操作count"><span class="nav-number">20.</span> <span class="nav-text">计数操作count</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#唯一值查询distinct"><span class="nav-number">21.</span> <span class="nav-text">唯一值查询distinct</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#指定字段有多个相同时，只取一个，返回指定字段的值组合成的数组"><span class="nav-number">21.1.</span> <span class="nav-text">指定字段有多个相同时，只取一个，返回指定字段的值组合成的数组</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#分组操作group"><span class="nav-number">22.</span> <span class="nav-text">分组操作group</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#更多分组功能"><span class="nav-number">22.1.</span> <span class="nav-text">更多分组功能</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#mapReduce"><span class="nav-number">23.</span> <span class="nav-text">mapReduce</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#游标"><span class="nav-number">24.</span> <span class="nav-text">游标</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#索引ensureIndex"><span class="nav-number">25.</span> <span class="nav-text">索引ensureIndex</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#建立索引"><span class="nav-number">25.1.</span> <span class="nav-text">建立索引</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#唯一索引"><span class="nav-number">25.2.</span> <span class="nav-text">唯一索引</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#组合索引"><span class="nav-number">25.3.</span> <span class="nav-text">组合索引</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#查看索引"><span class="nav-number">25.4.</span> <span class="nav-text">查看索引</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#按指定索引查询"><span class="nav-number">25.5.</span> <span class="nav-text">按指定索引查询</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#删除索引"><span class="nav-number">25.6.</span> <span class="nav-text">删除索引</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#性能分析函数explain"><span class="nav-number">26.</span> <span class="nav-text">性能分析函数explain</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#主从数据库部署"><span class="nav-number">27.</span> <span class="nav-text">主从数据库部署</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#创建主数据库master"><span class="nav-number">27.1.</span> <span class="nav-text">创建主数据库master</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#创建从数据库slave"><span class="nav-number">27.2.</span> <span class="nav-text">创建从数据库slave</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#后期指定主数据库源"><span class="nav-number">27.3.</span> <span class="nav-text">后期指定主数据库源</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#副本集replSet"><span class="nav-number">28.</span> <span class="nav-text">副本集replSet</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#创建第一个数据库服务器"><span class="nav-number">28.1.</span> <span class="nav-text">创建第一个数据库服务器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#创建第二个数据库服务器"><span class="nav-number">28.2.</span> <span class="nav-text">创建第二个数据库服务器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#初始化副本集"><span class="nav-number">28.3.</span> <span class="nav-text">初始化副本集</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#仲裁服务器"><span class="nav-number">28.4.</span> <span class="nav-text">仲裁服务器</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#分片技术"><span class="nav-number">29.</span> <span class="nav-text">分片技术</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#开启配置服务器config"><span class="nav-number">29.1.</span> <span class="nav-text">开启配置服务器config</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#开启路由服务器mongos"><span class="nav-number">29.2.</span> <span class="nav-text">开启路由服务器mongos</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#开启分片数据库服务器mongod"><span class="nav-number">29.3.</span> <span class="nav-text">开启分片数据库服务器mongod</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#服务配置"><span class="nav-number">29.4.</span> <span class="nav-text">服务配置</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#运维"><span class="nav-number">30.</span> <span class="nav-text">运维</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#安装部署为windows服务"><span class="nav-number">30.1.</span> <span class="nav-text">安装部署为windows服务</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#状态监控"><span class="nav-number">30.2.</span> <span class="nav-text">状态监控</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#静态统计"><span class="nav-number">30.2.1.</span> <span class="nav-text">静态统计</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实时统计"><span class="nav-number">30.2.2.</span> <span class="nav-text">实时统计</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#安全认证"><span class="nav-number">30.3.</span> <span class="nav-text">安全认证</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#备份和恢复"><span class="nav-number">30.4.</span> <span class="nav-text">备份和恢复</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考资料"><span class="nav-number">30.5.</span> <span class="nav-text">参考资料</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 – <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Raincal</span>

  

  
</div>


  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a></div>




        








        
      </div>
    </footer>

    

    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>







  






  















  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/npm/jquery-lazyload@1.9.7/jquery.lazyload.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.ui.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.4.1/dist/jquery.fancybox.min.js"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=6.6.0"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=6.6.0"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=6.6.0"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=6.6.0"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=6.6.0"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=6.6.0"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=6.6.0"></script>



  



  










  





  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  
  

  

  

  

  

  

  

</body>
</html>
